package com.market.fleamarket.controller;

import com.market.fleamarket.entity.Product;
import com.market.fleamarket.entity.User;
import com.market.fleamarket.entity.Order;
import com.market.fleamarket.service.ProductService;
import com.market.fleamarket.service.ReviewService;
import com.market.fleamarket.service.UserService;
import com.market.fleamarket.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.ArrayList;
import java.util.Random;
import java.util.stream.Collectors;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @PostMapping
    public Product addProduct(@RequestBody Product product) {
        return productService.save(product);
    }

    @GetMapping
    public List<Product> getAllProducts() {
        return productService.findAll();
    }

    @GetMapping("/{id}")
    public Object getProductById(@PathVariable Long id) {
        System.out.println("获取商品详情: ID = " + id);
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取商品信息
            Optional<Product> productOpt = productService.findById(id);
            if (!productOpt.isPresent()) {
                System.out.println("商品不存在: ID = " + id);
                result.put("error", "商品不存在");
                return result;
            }

            Product product = productOpt.get();
            System.out.println("商品信息: " + product.getName() + ", 状态: " + product.getStatus() + ", 用户ID: " + (product.getUser() != null ? product.getUser().getId() : "null"));

            // 确保商品关联的用户信息完整
            if (product.getUser() != null && product.getUser().getId() != null) {
                try {
                    // 从数据库重新加载完整的用户信息
                    Optional<User> userOpt = userService.findById(product.getUser().getId());
                    if (userOpt.isPresent()) {
                        product.setUser(userOpt.get());
                        System.out.println("重新加载用户信息: ID = " + product.getUser().getId() + ", 用户名: " + product.getUser().getUsername());
                    } else {
                        System.out.println("找不到商品关联的用户: ID = " + product.getUser().getId());
                    }
                } catch (Exception e) {
                    System.err.println("加载用户信息时出错: " + e.getMessage());
                    // 错误不阻止继续处理
                }
            } else {
                System.out.println("商品没有关联用户信息");
            }

            // 打印完整的商品对象，便于调试
            System.out.println("完整商品对象: " + product);
            System.out.println("商品图片URL: " + product.getImageUrl());

            result.put("product", product);

            // 检查商品是否可售
            boolean sellable = false;
            try {
                sellable = productService.isProductSellable(product);
                System.out.println("商品是否可售: " + sellable);
            } catch (Exception e) {
                System.err.println("检查商品可售状态时出错: " + e.getMessage());
                // 默认为不可售
            }
            result.put("sellable", sellable);

            // 获取卖家评分
            if (product.getUser() != null && product.getUser().getId() != null) {
                try {
                    Double avgScore = reviewService.getSellerAverageScore(product.getUser().getId());
                    System.out.println("卖家评分: " + avgScore);
                    result.put("sellerAvgScore", avgScore);
                } catch (Exception e) {
                    System.err.println("获取卖家评分时出错: " + e.getMessage());
                    e.printStackTrace();
                    result.put("sellerAvgScore", 0.0);
                    result.put("reviewError", "获取评分失败: " + e.getMessage());
                }
            } else {
                System.out.println("无法获取卖家评分: 卖家信息不完整");
                result.put("sellerAvgScore", 0.0);
            }

            // 获取买家评分
            try {
                Double buyerScore = reviewService.getProductBuyerResponseScore(id);
                System.out.println("买家评分: " + buyerScore);
                result.put("buyerResponseScore", buyerScore);
            } catch (Exception e) {
                System.err.println("获取买家评分时出错: " + e.getMessage());
                result.put("buyerResponseScore", 0.0);
            }

            // 打印最终返回的结果对象
            System.out.println("返回结果对象: " + result);

        } catch (Exception e) {
            System.err.println("处理商品详情时出现未知错误: " + e.getMessage());
            e.printStackTrace();
            result.put("error", "加载商品详情失败: " + e.getMessage());
        }

        return result;
    }

    @GetMapping("/page")
    public Page<Product> getProductsPage(@RequestParam(defaultValue = "0") int page,
                                         @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Product> products = productService.findAllProducts(pageable);

        // 为每个商品添加买家评分
        products.getContent().forEach(product -> {
            try {
                Double buyerScore = reviewService.getProductBuyerResponseScore(product.getId());
                product.setAdditionalProperty("buyerResponseScore", buyerScore);
            } catch (Exception e) {
                System.err.println("获取商品买家评分时出错: " + e.getMessage());
                product.setAdditionalProperty("buyerResponseScore", 0.0);
            }
        });

        return products;
    }

    @GetMapping("/category/{categoryId}")
    public Page<Product> getProductsByCategory(@PathVariable Long categoryId,
                                               @RequestParam(defaultValue = "0") int page,
                                               @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Product> products = productService.findByCategory(categoryId, pageable);

        // 为每个商品添加买家评分
        products.getContent().forEach(product -> {
            try {
                Double buyerScore = reviewService.getProductBuyerResponseScore(product.getId());
                product.setAdditionalProperty("buyerResponseScore", buyerScore);
            } catch (Exception e) {
                System.err.println("获取商品买家评分时出错: " + e.getMessage());
                product.setAdditionalProperty("buyerResponseScore", 0.0);
            }
        });

        return products;
    }

    @GetMapping("/search")
    public Page<Product> searchProducts(@RequestParam String keyword,
                                        @RequestParam(defaultValue = "0") int page,
                                        @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Product> products = productService.searchByName(keyword, pageable);

        // 为每个商品添加买家评分
        products.getContent().forEach(product -> {
            try {
                Double buyerScore = reviewService.getProductBuyerResponseScore(product.getId());
                product.setAdditionalProperty("buyerResponseScore", buyerScore);
            } catch (Exception e) {
                System.err.println("获取商品买家评分时出错: " + e.getMessage());
                product.setAdditionalProperty("buyerResponseScore", 0.0);
            }
        });

        return products;
    }

    @PostMapping("/{id}/approve")
    public Product approveProduct(@PathVariable Long id) {
        Product product = productService.findById(id).orElseThrow(() -> new RuntimeException("商品不存在"));
        product.setStatus("on_sale");
        return productService.save(product);
    }

    @PostMapping("/{id}/force-off")
    public Product forceOffProduct(@PathVariable Long id) {
        Product product = productService.findById(id).orElseThrow(() -> new RuntimeException("商品不存在"));
        product.setStatus("off_sale");
        return productService.save(product);
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteProduct(@PathVariable Long id, HttpSession session) {
        try {
            // 获取当前用户
            User user = (User) session.getAttribute("user");
            if (user == null) {
                Map<String, String> response = new HashMap<>();
                response.put("error", "请先登录");
                return ResponseEntity.status(401).body(response);
            }

            // 查找商品
            Optional<Product> productOpt = productService.findById(id);
            if (!productOpt.isPresent()) {
                Map<String, String> response = new HashMap<>();
                response.put("error", "商品不存在");
                return ResponseEntity.status(404).body(response);
            }

            Product product = productOpt.get();

            // 检查权限：只有商品所有者或管理员可以删除
            String role = (String) session.getAttribute("userRole");
            boolean isAdmin = "admin".equals(role) || "category_admin".equals(role);
            boolean isOwner = product.getUser() != null && product.getUser().getId().equals(user.getId());

            if (!isAdmin && !isOwner) {
                Map<String, String> response = new HashMap<>();
                response.put("error", "没有权限删除此商品");
                return ResponseEntity.status(403).body(response);
            }

            // 软删除：将商品状态设置为deleted
            product.setStatus("deleted");
            productService.save(product);

            Map<String, String> response = new HashMap<>();
            response.put("message", "商品已成功删除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> response = new HashMap<>();
            response.put("error", "删除失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    // ==== 用户管理自己商品的API ====

    /**
     * 获取当前用户发布的所有商品
     */
    @GetMapping("/my")
    public Page<Product> getMyProducts(HttpSession session,
                                       @RequestParam(defaultValue = "0") int page,
                                       @RequestParam(defaultValue = "10") int size) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            throw new RuntimeException("请先登录");
        }

        Pageable pageable = PageRequest.of(page, size);
        return productService.findByUserId(user.getId(), pageable);
    }

    /**
     * 发布新商品
     */
    @PostMapping("/publish")
    public Object publishProduct(@RequestBody Product product, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return java.util.Collections.singletonMap("error", "请先登录");
            }

            product.setUser(user);
            Product savedProduct = productService.publishProduct(product);
            return savedProduct;
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }

    /**
     * 更新商品状态（上架/下架）
     */
    @PostMapping("/{id}/status")
    public Object updateProductStatus(@PathVariable Long id,
                                      @RequestParam String status,
                                      HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return java.util.Collections.singletonMap("error", "请先登录");
            }

            // 检查状态是否有效
            if (!status.equals("on_sale") && !status.equals("off_sale")) {
                return java.util.Collections.singletonMap("error", "无效的状态值");
            }

            Product updatedProduct = productService.updateProductStatus(id, status, user.getId());
            return updatedProduct;
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }

    /**
     * 更新商品信息
     */
    @PutMapping("/{id}")
    public Object updateProduct(@PathVariable Long id,
                                @RequestBody Product productUpdate,
                                HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return java.util.Collections.singletonMap("error", "请先登录");
            }

            Product existingProduct = productService.findById(id)
                    .orElseThrow(() -> new RuntimeException("商品不存在"));

            // 验证是否是商品所有者
            if (!existingProduct.getUser().getId().equals(user.getId())) {
                return java.util.Collections.singletonMap("error", "您没有权限修改此商品");
            }

            // 更新商品信息，但保留原始用户和ID
            existingProduct.setName(productUpdate.getName());
            existingProduct.setDescription(productUpdate.getDescription());
            existingProduct.setPrice(productUpdate.getPrice());
            existingProduct.setCategory(productUpdate.getCategory());
            existingProduct.setValidUntil(productUpdate.getValidUntil());

            // 如果提供了新的图片URL，则更新
            if (productUpdate.getImageUrl() != null && !productUpdate.getImageUrl().isEmpty()) {
                existingProduct.setImageUrl(productUpdate.getImageUrl());
            }

            // 重置商品状态为待审核
            existingProduct.setStatus("pending");

            // 保存更新
            return productService.save(existingProduct);
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }

    /**
     * 获取随机推荐商品
     * 如果用户有订单，优先推荐同类商品，否则随机推荐
     * @param limit 推荐商品数量
     * @return 推荐商品列表
     */
    @GetMapping("/recommend")
    public List<Product> getRecommendProducts(@RequestParam(defaultValue = "4") int limit, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Product> recommendProducts = new ArrayList<>();

        try {
            // 如果用户已登录，尝试获取其订单中的商品类别
            if (user != null) {
                List<Order> userOrders = orderService.findByBuyerId(user.getId());

                if (!userOrders.isEmpty()) {
                    // 收集用户所有订单中的商品分类
                    List<Long> categoryIds = userOrders.stream()
                            .filter(order -> order.getProduct() != null && order.getProduct().getCategory() != null)
                            .map(order -> order.getProduct().getCategory().getId())
                            .distinct()
                            .collect(Collectors.toList());

                    if (!categoryIds.isEmpty()) {
                        // 创建一个集合存储所有可能的推荐商品
                        List<Product> candidateProducts = new ArrayList<>();

                        // 对每个分类，获取可售商品并添加到候选集合中
                        Random random = new Random();
                        for (Long categoryId : categoryIds) {
                            Pageable pageable = PageRequest.of(0, 10); // 每个分类获取最多10个商品
                            Page<Product> categoryProducts = productService.findByCategory(categoryId, pageable);

                            if (categoryProducts.hasContent()) {
                                List<Product> availableProducts = categoryProducts.getContent().stream()
                                        .filter(p -> productService.isProductSellable(p))
                                        .collect(Collectors.toList());

                                candidateProducts.addAll(availableProducts);
                            }
                        }

                        // 打乱候选商品列表
                        Collections.shuffle(candidateProducts, random);

                        // 从候选列表中选择不重复的商品
                        Set<Long> selectedProductIds = new HashSet<>();
                        for (Product product : candidateProducts) {
                            if (selectedProductIds.contains(product.getId())) {
                                continue; // 跳过已选择的商品
                            }

                            recommendProducts.add(product);
                            selectedProductIds.add(product.getId());

                            if (recommendProducts.size() >= limit) {
                                break; // 已经选择了足够的商品
                            }
                        }
                    }
                }
            }

            // 如果推荐商品不足，随机补充
            if (recommendProducts.size() < limit) {
                Pageable pageable = PageRequest.of(0, 50); // 获取更多商品以供随机选择
                Page<Product> allProducts = productService.findOnSaleValidProducts(pageable);

                if (allProducts.hasContent()) {
                    // 筛选出尚未推荐的商品
                    Set<Long> recommendedIds = recommendProducts.stream()
                            .map(Product::getId)
                            .collect(Collectors.toSet());

                    List<Product> availableProducts = allProducts.getContent().stream()
                            .filter(p -> !recommendedIds.contains(p.getId())) // 排除已推荐的商品
                            .collect(Collectors.toList());

                    // 打乱可用商品列表
                    Collections.shuffle(availableProducts);

                    // 添加到推荐列表中
                    for (Product product : availableProducts) {
                        recommendProducts.add(product);
                        if (recommendProducts.size() >= limit) {
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("获取推荐商品时出错: " + e.getMessage());
        }

        return recommendProducts;
    }
} 